package b;

import java.util.ArrayList;
import java.util.List;

public class _1_N皇后 {
    char[][] gird;
    List<List<String>> res = new ArrayList<>();
    public List<List<String>> solveNQueens(int n) {
        char[][] gird = new char[n][n];
        this.gird = gird;
        //自己模拟一个初始gird
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                gird[i][j] = '.';
            }
        }
        //按行走，省力判断
        backTrack(0);
        return res;
    }
    public void backTrack(int row) {
        if (row == gird.length) {
            return;
        }

        for (int col = 0; col < gird.length; col++) {
            if (!isVaild(row, col))continue;
            gird[row][col] = 'Q';
            backTrack(row + 1);
            gird[row][col] = '.';
        }
    }
    //因为皇后从第一行向下放的，所以只判断上方：’左上 右上 直上‘
    boolean isVaild(int row, int col) {
        //左上
        for (int i = row - 1, j = col - 1; i >= 0 & j >= 0; i--, j--) {
            if (gird[i][j] == 'Q')
                return false;
        }
        //右上
        for (int i = row - 1, j = col + 1; i >= 0 & j < gird.length; i--, j++) {
            if (gird[i][j] == 'Q')
                return false;
        }
        //直上
        for (int i = row - 1; i >= 0; i--) {
            if (gird[i][col] == 'Q')
                return false;
        }
        return true;
    }
}
